package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.exception.CustException;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO dto) {
        // 1 判断手机号 密码是否为空
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if(StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(password)){
            // 此时说明是正常登录的
            // 1.1 查询该手机号对应的用户是否存在
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if(apUser ==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该手机号对应的用户不存在!");
            }
            // 1.2 判断输入的密码和数据苦中的密码是否匹配
            String dsPwd = apUser.getPassword();
            String salt = apUser.getSalt();
            String encodePwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!dsPwd.equals(encodePwd)){
                // 说明密码不一致
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码不正确!");
            }
            // 1.3 登录上了之后 颁发token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map<String,Object> result = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            result.put("token",token);
            result.put("user",apUser);
            return ResponseResult.okResult(result);
        }else {
            // 临时登录
            // 2.1 获取设备id
            Integer equipmentId = dto.getEquipmentId();
            if (equipmentId == null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
            // 2.2 通过设备登录的按照id=0颁发token
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> result = new HashMap<>();
            result.put("token",token);
            return ResponseResult.okResult(result);
        }
    }
}